package servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {

        //获取指定名字的参数
        String username = config.getInitParameter("username");
        System.out.println(username);

        //获取参数名组成的Enumeration
        Enumeration<String> parameterNames = config.getInitParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            System.out.println(name);
        }

        //获取名字
        String servletName = config.getServletName();
        System.out.println(servletName);

        ServletContext servletContext = config.getServletContext();
        String namespace = servletContext.getInitParameter("namespace");
        System.out.println(namespace);

        String realPath = servletContext.getRealPath("");
        System.out.println(realPath);

        String contextPath = servletContext.getContextPath();
        System.out.println(contextPath);

        InputStream resourceAsStream = servletContext.getResourceAsStream("/");

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        HttpSession session = req.getSession();
        ServletContext servletContext = req.getSession().getServletContext();

        System.out.println("aservice service, SESSION:" + session.getId());

        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
            }
        } else {
            Cookie cookie = new Cookie("girl", "wwj");
            //设置该属性 cookie永久保存，不设置就是临时的 正数为有效秒数 0为立即删除该cookie 负数为不存储该cookie
            cookie.setMaxAge(3600 * 24 * 30);
            //设置的路径适用于当前目录和子目录
            cookie.setPath(req.getContextPath());
            resp.addCookie(cookie);
        }
    }

    @Override
    public void destroy() {
        System.out.println("aserviet destroy");
    }


}




